/**
 * Created by Max-Goday on 15/7/23.
 */


$(document).ready(function() {

	//init google code prettify
	prettyPrint();

	//Init Repository List
	request_AJAX(getServiceURL('RepoService', 'getAllRepo'),{}, function(data) {

		var repos = ALL_REPOSITORY_PROPERTIY = data.result;

		for (var i = 0; i < repos.length; i ++) {
			$('#repository_dropdown_list').append($("<li><a index=\"" + i + "\" href=\"javascript:void(0);\" onclick=\"onclickRepoChange(this)\">" + repos[i].repo_name + "</a></li>"));
		}

		var init_a = $('#repository_dropdown_list').find('a[index=0]');
		if (init_a) onclickRepoChange(init_a);

	}, null, true)

	$('#add-repo-form').formValidation({
		framework: 'bootstrap',
		icon: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			repo_name: {
				validators: {
					notEmpty: {
						message: 'The Repo Name is required'
					}
				}
			},
			repo_url: {
				validators: {
					notEmpty: {
						message: 'The Git URL is required'
					}
				}
			},
			repo_builder_config_dir : {
				validators: {
					notEmpty: {
						message: 'The porject builder file path is required'
					}
				}
			}
		}
	}).on('success.form.fv', function(e) {
		e.preventDefault();

		request_FORM($('#add-repo-form'), getServiceURL('RepoService', 'createRepo'), {
		}, function(data) {
			noty('success', 'Success', 'Repository added, waiting to progress!');
		}, function(data) {
			noty('error', 'Error', 'Add repository failed! Press F12 to see detail.');
			console.log(data);
		});

		$('#add-repo-modal').modal('toggle');
	});
});

function onclickRepoChange(e) {
	$(e).parent().parent().parent().find('a:first').html($(e).html());

	REPOISOTRY_IDENTIFY = $(e).html();
	CURRENT_REPOSITORY_PROPERTIY = ALL_REPOSITORY_PROPERTIY[$(e).attr('index')];

	$("#git-grid").bootgrid('reload');

	$("#cluster-grid").bootgrid('reload');

}

var _git_log_grid = $("#git-grid").bootgrid({
	ajax : true,
	post : function() {
		return {
			repo : REPOISOTRY_IDENTIFY
		};
	},
	url : getContextPath() + "/api/s/RepoService/getRepoLogs",
	rowCount : 15,
	formatters : {
		"commands" : function(column, row) {
			return "<button title=\"Deploy\" type=\"button\" class=\"btn btn-xs btn-default glyphicon glyphicon-cloud\" data-row-id=\"" + row.c_id + "\"><span class=\"fa fa-pencil\"></span></button> " +
				"<button title=\"Detail\" type=\"button\" class=\"btn btn-xs btn-default glyphicon glyphicon-th-list\" data-row-id=\"" + row.c_id + "\"><span class=\"fa fa-trash-o\"></span></button>";
		}
	}
}).on("loaded.rs.jquery.bootgrid", function() {
	/* Executes after data is loaded and rendered */
	_git_log_grid.find(".glyphicon-cloud").on("click", function(e) {

		show_deploy_modal($(this).data("row-id"));

	}).end().find(".glyphicon-th-list").on("click", function(e) {

		show_commit_detail_modal($(this).data("row-id"));

	});
});

var _cluster_grid = $("#cluster-grid").bootgrid({
	ajax : true,
	post : function() {
		return {
			repo : REPOISOTRY_IDENTIFY
		};
	},
	url : getContextPath() + "/api/s/ClusterService/getClusterByRepo",
	rowCount : 15,
	formatters : {
		"commands" : function(column, row) {
			return "<button title=\"Deploy\" type=\"button\" class=\"btn btn-xs btn-default glyphicon glyphicon-cloud\" data-row-id=\"" + row.IP + "\"><span class=\"fa fa-pencil\"></span></button> " +
				"<button title=\"Edit\" type=\"button\" class=\"btn btn-xs btn-default glyphicon glyphicon-pencil\" data-row-id=\"" + row.IP + "\"><span class=\"fa fa-trash-o\"></span></button>";
		}
	}
}).on("loaded.rs.jquery.bootgrid", function() {
	/* Executes after data is loaded and rendered */
	_cluster_grid.find(".glyphicon-cloud").on("click", function(e) {
		alert('pressed deploy at ' + $(this).data("row-id"))

	}).end().find(".glyphicon-pencil").on("click", function(e) {
		alert('pressed edit at ' + $(this).data("row-id"))

	});
});

function show_deploy_modal(commit_id) {

	request_AJAX(getServiceURL('ClusterService', 'getClusterByRepo'), {
		repo : CURRENT_REPOSITORY_PROPERTIY.repo_name
	}, function(data) {

		var options, i, server;

		for (i = 0; i < data.total; i++) {
			server = data.rows[i];
			options += '<option value="' + server.IP + '">' + server.Name + '(' + server.IP + ') Deploy Dir:' + server['Deploy Dir'] +  '</option>';
		}



		var html =
			'<select id="cluster_server_selector" multiple="multiple">'
				+ options + '\
			</select>\
			<button type="button" class="btn btn-primary" autocomplete="off">\
				Deploy\
			</button>';


		var win = getModalWin("deploy_win", 'Select Cluster Server(s)', html);
		win.show();

		$('#cluster_server_selector').multiselect({
			buttonWidth: '490px'
		});

		win.find('button.btn-primary').on('click', function() {

			var deploy_server_ips = [];

			$('#cluster_server_selector option:selected').each(function() {

				deploy_server_ips.push($(this).val());

			});

			if (deploy_server_ips.length == 0) {
				noty('error', 'Warning', 'Please Select Cluster-Server!');
				return;
			}

			win.close();

			request_AJAX(getServiceURL('RepoService', 'deploy'), {
				repo_name : REPOISOTRY_IDENTIFY,
				commit_id : commit_id,
				deploy_server_ips : deploy_server_ips.join(', ')
			}, function(data) {
				alert('Deploy Success!');
			}, function(data) {
				noty('error', 'Error', 'Oops!Someting wrong with deployment, Press F12 to see detail.');
				console.log(data.responseText)
			}, null);
		})

	}, function(data) {
		noty('error', 'Error', 'Oops!Someting wrong with deployment, Press F12 to see detail.');
		console.log(data.responseText)
	}, true);


}

function show_commit_detail_modal(commit_id) {

	if ($("#commit_detail_grid")) {
		$("#commit_detail_grid").bootgrid('destroy');
	}

	var commit_detail_list =
		'<table id="commit_detail_grid" class="table table-condensed table-hover table-striped">\
			<thead>\
				<tr>\
					<th data-column-id="name" data-sortable="false" data-formatter="name">File List</th>\
				</tr>\
			</thead>\
		</table>';

	getModalWin("commit_detail", 'Commit Details', commit_detail_list, true).show();

	var _commit_detail_grid = $("#commit_detail_grid").bootgrid({
		ajax : true,
		post : function() {

			return {
				repo_name : REPOISOTRY_IDENTIFY,
				commit_id : commit_id,
				_st : new Date().getTime()

			};
		},
		url : getContextPath() + "/api/s/RepoService/getCommitDetail",
		navigation : 2,
		rowCount : 9999,
		formatters : {
			name : function(column, row) {

				return row.changetype + " - " + row.name;

			}
		}
	});

}

function onclickClusterAdd() {

	if (!REPOISOTRY_IDENTIFY) {
		noty('error', 'Warning', 'Please select a repository!');
		return;
	}

	var html = '<form id="add-cluster-server-form">\
					<div class="form-group">\
						<label for="server_name" class="control-label">Server Name:</label>\
						<input type="text" name="server_name" class="form-control" id="server_name">\
					</div>\
					<div class="form-group">\
						<label for="server_ip" class="control-label">Server IP:</label>\
						<input type="text" name="server_ip" class="form-control" id="server_ip">\
					</div>\
					<div class="form-group">\
						<label for="server_ssh_port" class="control-label">Server SSH Port:</label>\
						<input type="text" name="server_ssh_port" class="form-control" id="server_ssh_port">\
					</div>\
					<div class="form-group">\
						<label for="server_login_id" class="control-label">Server Login ID:</label>\
						<input type="text" name="server_login_id" class="form-control" id="server_login_id">\
					</div>\
					<div class="form-group">\
						<label for="server_login_password" class="control-label">Server Login Password:</label>\
						<input type="text" name="server_login_password" class="form-control" id="server_login_password">\
					</div>\
					<div class="form-group">\
						<label for="app_deploy_dir" class="control-label">App Deploy Dir:</label>\
						<input type="text" name="app_deploy_dir" class="form-control" id="app_deploy_dir">\
					</div>\
					<div class="form-group">\
						<label for="server_des" class="control-label">Description:</label>\
						<textarea name="server_des" class="form-control" id="server_des"></textarea>\
					</div>\
					<button id="cluster-server-add-btn" type="submit" class="btn btn-primary">Submit</button>\
				</form>';

	getModalWin("add_repo_cluster", 'Add New Cluster Server For \"' + REPOISOTRY_IDENTIFY + '\"', html).show();

	$('#add-cluster-server-form').formValidation({
		framework: 'bootstrap',
		icon: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			server_name: {
				validators: {
					notEmpty: {
						message: 'The Server Name is required'
					}
				}
			},
			server_ip: {
				validators: {
					notEmpty: {
						message: 'The Server IP is required'
					}
				}
			},
			server_login_id : {
				validators: {
					notEmpty: {
						message: 'The Server Login ID is required'
					}
				}
			},
			server_login_password : {
				validators: {
					notEmpty: {
						message: 'The Server Login Password is required'
					}
				}
			},
			app_deploy_dir : {
				validators: {
					notEmpty: {
						message: 'The App Deploy DIR is required'
					}
				}
			}
		}
	}).on('success.form.fv', function(e) {
		e.preventDefault();

		request_FORM($('#add-cluster-server-form'), getServiceURL('ClusterService', 'addClusterServerInfo'), {
			repo_name : REPOISOTRY_IDENTIFY
		}, function(data) {
			noty('success', 'Success', 'Cluster server info added, refresh gird!');
		}, function(data) {
			noty('error', 'Error', 'Add cluster server failed! Press F12 to see detail.');
			console.log(data.responseText);
		});

		$('#add_repo_cluster_modal').modal('toggle');

	});

}